﻿using IMES.Common.Domain.DariusModel;
using IMES.Common.Domain.SirModel;
using IMES.Common.Dtos;
using IMES.Common.Infrastructure;
using MediatR;
using Mysqlx.Crud;
using System.Collections.Generic;

namespace Darius.API.Application.Commands.Order
{
    public class OrderProGetHandler : IRequestHandler<OrderProGetCommand, ResultT<GetOrderDto>>
    {
        private readonly IBaseRepositorys<SaleOrders> saleorderrepository;
        private readonly IBaseRepositorys<OrderDetails> orderdetailrepository;
        private readonly IBaseRepositorys<Product> productrepository;

        public OrderProGetHandler(IBaseRepositorys<SaleOrders> saleorderrepository, IBaseRepositorys<OrderDetails> orderdetailrepository, IBaseRepositorys<Product> productrepository)
        {
            this.saleorderrepository = saleorderrepository;
            this.orderdetailrepository = orderdetailrepository;
            this.productrepository = productrepository;
        }
        public async Task<ResultT<GetOrderDto>> Handle(OrderProGetCommand request, CancellationToken cancellationToken)
        {
            var result= new ResultT<GetOrderDto>() { Code=(int)CodeEnum.search};
            var list = (from a in saleorderrepository.GetAll()
                       where a.OrderId == request.OrderId
                       select new GetOrderDto()
                       {
                           OrderId = a.OrderId,
                           OrderNo = a.OrderNo,
                           OrderNotes = a.OrderNotes,
                           CreateName=a.CreateName,
                           CreateDate=a.CreateDate,
                           OrderDetail =new List<GetOrderDetailDtos>(),
                       }).FirstOrDefault();
            if (list != null)
            {
                list.OrderDetail = (from a in saleorderrepository.GetAll()
                                     join b in orderdetailrepository.GetAll() on a.OrderId equals b.OrderId
                                     join c in productrepository.GetAll() on b.ProductNumber equals c.ProductNumber
                                     where b.OrderId == request.OrderId
                                     select new GetOrderDetailDtos()
                                     {
                                         OrderDetailId = b.OrderDetailId,
                                         OrderId=a.OrderId,
                                         OrderNo=a.OrderNo,
                                         WorkOrder=b.WorkOrder,
                                         ProductNumber=b.ProductNumber,
                                         ProductName=c.ProductName,
                                         ProductNum=b.ProductNum,
                                     }).ToList();
            }
            result.Data1 = list;
            return result;

        }
    }
}
